#include "surface.h"

#include "scene.h"
#include "view.h"
#include "entity.h"


namespace Opl{ namespace Gui {

		class SurfacePrivate{
		public:
			SurfacePrivate() {}
			~SurfacePrivate() {}
			QGraphicsProxyWidget *childItem;
			qreal scale;
		};


		Surface::~Surface()
		{
			O_PRIVATE_DELETE;
		}

		QGraphicsProxyWidget *Surface::childItem() const
		{
			O_D(Surface);
			return d->childItem;
		}


		Surface::Surface(Scene *scene, const QPointF &a, const QPointF &b)
			: Entity(QRectF(-0.5, -0.5, 1.0, 1.0)),O_PRIVATE_CREATE(Surface)

		{

			O_D(Surface);
			setPosition(a, b);

			d->scale = 0.8;

            d->childItem = 0;
            QWidget *childWidget = 0;

            QWidget *widget = new QWidget;
            QPushButton *button = new QPushButton("Open Sesame", widget);
            widget->setLayout(new QVBoxLayout);
            widget->layout()->addWidget(button);
            childWidget = widget;

            if (!childWidget)
                return;

            childWidget->installEventFilter(scene);

            d->childItem = new ProxyWidget(this);
            d->childItem->setWidget(childWidget);
            d->childItem->setCacheMode(QGraphicsItem::ItemCoordinateCache);

            QRectF rect = d->childItem->boundingRect();
            QPointF center = rect.center();

            qreal scale = qMin(d->scale / rect.width(), d->scale / rect.height());
            d->childItem->translate(0, -0.05);
            d->childItem->scale(scale, scale);
            d->childItem->translate(-center.x(), -center.y());
        }

        void Surface::childResized()
        {
            O_D(Surface);
            QRectF rect = d->childItem->boundingRect();

            QPointF center = rect.center();

            qreal scale = qMin(d->scale / rect.width(), d->scale / rect.height());
            d->childItem->resetMatrix();
            d->childItem->translate(0, -0.05);
            d->childItem->scale(scale, scale);
            d->childItem->translate(-center.x(), -center.y());

            // refresh cache size
            d->childItem->setCacheMode(QGraphicsItem::NoCache);
            d->childItem->setCacheMode(QGraphicsItem::ItemCoordinateCache);
        }



    };};
